package com.tzm.lucene.test01;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 *  创建索引步骤:
 *
 *  1. 创建一个Directory对象，指定索引库保存的位置
 *  2. 基于Directory对象创建一个IndexWriter对象
 *  3. 读取磁盘上的文件，对应每个文件创建一个文档对象
 *  4. 向文档对象添加域
 *  5. 把文档对象写入索引库
 *  6. 关闭IndexWriter对象
 */
public class Indexer {

    public static void main(String[] args) throws IOException {
        Directory indexDir = FSDirectory.open(Paths.get("D:\\temp\\index"));
        IndexWriter writer = new IndexWriter(indexDir, new IndexWriterConfig());
        File searchDir = new File("D:\\temp\\searchsource");
        File[] files = searchDir.listFiles();

        for (File f : files) {

            String name = f.getName();
            String path = f.getPath();
            String content = new String(Files.readAllBytes(f.toPath()));
            long size = Files.size(f.toPath());
            Document document = new Document();
            document.add(new TextField("name", name, Field.Store.YES));
            document.add(new TextField("path", path, Field.Store.YES));
            document.add(new TextField("content", content, Field.Store.YES));
            document.add(new TextField("size", size + "", Field.Store.YES));
            writer.addDocument(document);
        }
        writer.close();
    }

}
